package com.rlyy.rsj.job;

import com.rlyy.rsj.db.PostgresqlConn;
import com.rlyy.rsj.service.OrgpService;
import com.rlyy.rsj.utils.AddressHelper;
import com.rlyy.rsj.utils.DistributeLock;
import com.rlyy.rsj.utils.RedisKeyFactory;
import com.rlyy.rsj.utils.RedisUtils;
import common.util.DateTimeFormatterUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.sql.Connection;
import java.sql.SQLException;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.Objects;

import static com.rlyy.rsj.utils.DistributeLock.oneMinute;


@Component
public class DoUpStatusJob implements IScheduler {
    private static final Logger logger = LoggerFactory.getLogger(DoUpStatusJob.class);
    private static final OrgpService orgpInfoService = OrgpService.getInstance();
    private static final String LOCK_KEY = RedisKeyFactory.wrapJobKey(DoUpStatusJob.class.getName());
    private static final String STATUS_KEY = RedisKeyFactory.wrapJobKey("orgp_status");
    private static final String HEALTH_KEY = RedisKeyFactory.wrapJobKey("orgp_health");
    /**
     * 数据库连接
     */
    @Value("#{dataSource.getConnection()}")
    private Connection connection;


    /**
     * 开始调度任务、10秒执行一次
     */
    @Override
    @Scheduled(fixedRate = 1000 * 10)
    public void scheduler() {
        boolean lock = DistributeLock.lock(LOCK_KEY, DateTimeFormatterUtil.dateTimeToString(LocalDateTime.now()), oneMinute);
        if (lock) {
            logger.info("{}-开始定时任务:{}",LOCAL_INFO, "DoUpStatusJob");
            try {
                orgpInfoService.updateForTimmer(this.getVerifiedConnection());
            } catch (SQLException e) {
                logger.error(LOCAL_INFO+"-DoUpStatusJob  error ", e);
            }
            //统计完成状态
            RedisUtils.set(STATUS_KEY, DateTimeFormatterUtil.dateTimeToString(LocalDateTime.now()), -1);
            DistributeLock.unlock(LOCK_KEY);
        } else {
            logger.warn("{}-未执行DoUpStatusJob!",LOCAL_INFO);
        }
        //统计存活状态
        RedisUtils.hset(HEALTH_KEY, LOCAL_INFO, DateTimeFormatterUtil.dateTimeToString(LocalDateTime.now()));
    }


    /**
     * 检查数据库连接
     */
    private Connection getVerifiedConnection() {
        try {
            if (Objects.isNull(connection) || connection.isClosed()) {
                connection = PostgresqlConn.getConnection();
            }
        } catch (SQLException e) {
            e.printStackTrace();
            logger.error("数据库连接已关闭、重新获取失败");
        }
        return connection;
    }
}
